/*
 * @Author: 曾洪昌
 * @Date: 2020-08-01 10:18:18
 * @LastEditTime: 2021-12-27 14:52:55
 * @LastEditors: Sam
 * @Description: 空运/海运/快递下单 清关发票的相关数据格式
 * @FilePath: \resourcesf:\thework\tofba-client\src\utils\invoice-table.js
 * @V1.0
 */
import { clone } from './clone'
import { getToken } from '@/utils/auth'
import globalData from '@/utils/config'
import Handsontable from 'handsontable'
import { MessageBox, Message } from 'element-ui'
// import { Upload, MessageBox, Message } from 'element-ui'
import { customerskuinfoList } from '@/api/myProfile'
// let liquidationHot // 清关发票handsonTable实例
// const liquidationData = [] // 清关发票数据全局变量
// let current_selected_x // 当前选中的行
import store from '@/store'
const selectSku = {} // 此次搜索SKU信息全局变量
const selectSkuList = [] // 此次搜索SKU信息全局变量
// const skuList = [] // 存储所有SKU集合用来校验是否重复出现
const SKU_UNIT = Object.values(store.getters.publicData.skuUnitMap)
// const JAPAN_LINE = [16, 17, 99, 115, 229, 227, 226, 136, 115, 88, 84, 34, 33];// 日本专线
// const PATTERN0 = new RegExp(/\s+/g, 'g')
// const PATTERN1 = new RegExp(/\u00A0+/g, 'g')
/**
 * 自定义渲染
 */

export function skuCellRenderer (
  instance,
  td,
  row,
  col,
  prop,
  value,
  cellProperties
) {
  Handsontable.renderers.HtmlRenderer.apply(this, arguments)
  td.style.backgroundColor = '#fff'
  removeClass(td, 'htInvalid')
}

function hasClass (elem, cls) {
  cls = cls || ''
  if (cls.replace(/\s/g, '').length === 0) return false // 当cls没有参数时，返回false
  return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ')
}

function removeClass (elem, cls) {
  if (hasClass(elem, cls)) {
    let newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' '
    while (newClass.indexOf(' ' + cls + ' ') >= 0) {
      newClass = newClass.replace(' ' + cls + ' ', ' ')
    }
    elem.className = newClass.replace(/^\s+|\s+$/g, '')
  }
}

function addClass (e, cls) {
  if (!hasClass(e, cls)) {
    e.className = e.className === '' ? cls : e.className + ' ' + cls
  }
}
const otherHeader = [
  `<span>采购单价（RMB）</span>
  <a name="purchasingPrice"  title="
  此处请填写实际采购货值(以人民币为单位)，我司将以
  此货值投保，如有货损，我司也将以此货值理赔。
  切勿虚报，否则理赔可能不被受理。" style="font-size:16px" class="el-icon-question icon-absolute text-yellow">
  </a>
   `,
  `<span name="declareValue">申报单价</span>
  <a title="此处请填写用来向目的国进口清关用的申报货值,
  我司建议：此货值请勿低过线上销售价的30%，
  同时我司郑重声明：一切因您货值低报而产生的延误、
  扣关甚至罚没等责任，将由您自行承担"
  style="font-size:16px"
  class="el-icon-question icon-absolute text-yellow" />`,
  '<span name="imgUrl">SKU图片</span>'
]
const JapanLineHeader = [
  '<span class="noRedTitle">FNSKU</span>',
  '<span  name="purchasingPrice">采购单价（RMB）</span>',
  '<span  name="declareValue">ASIN售价</span>',
  '<span  name="distributionMaterialCount">配送料</span>',
  '<span  name="productLotCount">出品手数料</span>',
  '<span  name="imgUrl">SKU图片</span>',
  '<span  name="sellpriceScreenshot">售价截图</span>',
  '<span  name="incomeScreenshot">收益截图</span>'
]
const fbaHead = [
  '<span name="shipmentId">Shipment ID</span>',
  '<span name="referenceId">Reference ID</span>'
]
const noFbaHead = [
  '<span class="noRedTitle" name="shipmentId">Shipment ID</span>',
  '<span class="noRedTitle" name="referenceId">Reference ID</span>'
]

const colHeaders = [
  '<span name="sku">SKU</span>',
  '<span name="declareNameEn">英文品名</span>',
  '<span name="declareNameCn">中文品名</span>',
  '<span name="brand">品牌</span>',
  '<span name="material">材质</span>',
  '<span name="purpose">用途</span>',
  '<span name="customsCode">出口报关编码</span>',
  '<span name="hscode">清关编码</span>',
  '<span class="noRedTitle">ASIN/销售链接</span>',
  '<span class="noRedTitle">是否带电</span>',
  '<span name="model">型号</span>',
  '<span name="num">数量</span>',
  `<span name="measurementUnit">单位
  <a name="purchasingPrice"  title="与亚马逊销售单位一致。" style="font-size:16px" class="el-icon-question icon-absolute text-yellow">
  </a>
  </span>`,
  `<span class="noRedTitle" name="perSuitNum">每套个数<a name="purchasingPrice"  title="为符合国内报关要求，如售卖单位是套（或组等），则需要填写套（或组等）内个数。" style="font-size:16px" class="el-icon-question icon-absolute text-yellow">
  </a></span>`
]

export {
  otherHeader,
  JapanLineHeader,
  fbaHead,
  noFbaHead,
  colHeaders,
  selectSku,
  selectSkuList
}

/**
 * @description: 表格合并
 * @param {Object} obj
 * @return {Object}
 */
export async function getSpanArr (obj, isVip) {
  console.log('%cobj: ', 'color: #fff; background: #000;', obj)
  // 数据排序，以便合并

  if (obj && obj.tableData && obj.tableData.length > 0) {
    let spanArr = []
    let pos = 0
    console.log('obj.tableData :>> ', obj.tableData)

    obj.tableData.sort(
      (a, b) =>
        a.cartonNo.slice(a.cartonNo.lastIndexOf('U') + 1) -
        b.cartonNo.slice(a.cartonNo.lastIndexOf('U') + 1)
    )
    spanArr = []
    pos = 0
    for (var i = 0; i < obj.tableData.length; i++) {
      if (i === 0) {
        spanArr.push(1)
        pos = 0
      } else {
        // 判断当前元素与上一个元素是否相同,因合并第一个所以[0]
        if (obj.tableData[i]['cartonNo'] === obj.tableData[i - 1]['cartonNo']) {
          spanArr[pos] += 1
          spanArr.push(0)
        } else {
          spanArr.push(1)
          pos = i
        }
      }
    }
    obj.spanArr = clone(spanArr)
    // console.log('%cspanArr: ', 'color: #fff; background: #ccc;', spanArr)
    obj.pos = clone(pos)
    await changeCartonNo(obj, isVip)
    return obj
  }
}

/**
 * @description: 修改表格数据
 * @param {Object} obj
 * @return {Object}
 */
export function changeCartonNo (obj, isVip) {
  if (isVip) {
    return obj
  }
  console.log('%cchangeCartonNo: ', 'color: #ccc; background: #000;', obj)
  const rules = obj.rule || 'U000001'
  for (const i of obj.tableData) {
    const a = '00000'
    const index = i.cartonNo.lastIndexOf('U') + 1
    const boxNum = parseInt(i.cartonNo.slice(index)).toString()
    const cartonNo = `${obj.shipmentId}U${a.slice(
      0,
      rules.length - boxNum.length - 1
    ) + boxNum}`
    i.cartonNo = cartonNo
  }
  return obj
}
